import { http } from '@/utils/request';
import type { ApiResponse } from '@/types';

// 提交记录相关类型定义
export interface Submission {
  id: number;
  user_id: number;
  question_id: number;
  language: string;
  language_name: string;
  status: string;
  status_name: string;
  score: number;
  execution_time?: number;
  memory_used?: number;
  error_message?: string;
  created_at: string;
  user: {
    id: number;
    username: string;
    avatar: string;
  };
  question?: {
    id: number;
    title: string;
  };
}

export interface SubmissionDetail extends Submission {
  code: string;
  judge_result?: {
    test_cases: Array<{
      id: number;
      status: string;
      execution_time: number;
      memory_used: number;
      input?: string;
      output?: string;
      expected?: string;
      error_message?: string;
    }>;
    summary: {
      total_test_cases: number;
      passed_test_cases: number;
      max_execution_time: number;
      max_memory_used: number;
    };
  };
}

export interface SubmissionListResponse {
  submissions: Submission[];
  pagination: {
    page: number;
    page_size: number;
    total: number;
    total_page: number;
  };
}

export interface SubmissionQuery {
  page?: number;
  page_size?: number;
  language?: string;
  status?: string;
  user_id?: string;
}

export const submissionApi = {
  // 获取题目的提交记录列表
  getSubmissions(questionId: number, params?: SubmissionQuery): Promise<ApiResponse<SubmissionListResponse>> {
    return http.get(`/v1/submissions/question/${questionId}`, { params });
  },

  // 获取提交记录详情
  getSubmissionDetail(submissionId: number): Promise<ApiResponse<SubmissionDetail>> {
    return http.get(`/v1/submissions/${submissionId}`);
  },

  // 获取用户的提交记录
  getUserSubmissions(userId: number, params?: SubmissionQuery): Promise<ApiResponse<SubmissionListResponse>> {
    return http.get(`/v1/users/${userId}/submissions`, { params });
  },

  // 获取提交记录排名信息
  getSubmissionRanking(submissionId: number): Promise<ApiResponse<{
    time_rank: number, 
    memory_rank: number, 
    total_count: number,
    time_distribution: number[],
    memory_distribution: number[]
  }>> {
    return http.get(`/v1/execution/ranking/${submissionId}`);
  },
};
